package com.reebake.ideal.servlet.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.BooleanUtil;
import com.reebake.ideal.servlet.properties.CorsProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;

/**
 * 配置CORS,spring-security启用默认cors可以共享
 */
@Configuration
@ConditionalOnProperty(prefix = "mvc.cors", name = "enabled", havingValue = "true")
public class CorsConfig implements WebMvcConfigurer {

    @Autowired
    private CorsProperties corsProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        if(BooleanUtil.isFalse(corsProperties.getEnabled())) {
            return;
        }
        for(Map.Entry<String, CorsConfiguration> entry : corsProperties.getConfigurations().entrySet()) {
            String mapping = entry.getKey();
            CorsConfiguration cc = entry.getValue();
            registry.addMapping(mapping)
                    .allowedOriginPatterns(ArrayUtil.toArray(cc.getAllowedOriginPatterns(), String.class))
                    .allowedMethods(ArrayUtil.toArray(cc.getAllowedMethods(), String.class))
                    .allowedHeaders(ArrayUtil.toArray(cc.getAllowedHeaders(), String.class))
                    .allowCredentials(cc.getAllowCredentials())
                    .maxAge(cc.getMaxAge());
        }
    }
}

